package cn.edu.imut.service;

import cn.edu.imut.bean.AdminBean;
import cn.edu.imut.bean.UserBean;
import cn.edu.imut.dao.AdminDao;
import cn.edu.imut.dao.UserDao;
import lombok.SneakyThrows;

import java.io.*;
import java.util.Scanner;

public class Userservice {
    private final UserDao userdao = new UserDao();
    private final AdminDao adminDao = new AdminDao();
    private final Scanner sc = new Scanner(System.in);

    /**
     * 用户注册
     */
    public void register() {
        System.out.println("请输入新账号：");
        String username = sc.next();

        if (userdao.getUserByUsername(username) != null) {
            System.out.println("该账号已存在！");
            return;
        }

        System.out.println("请输入密码：");
        String password = sc.next();

        System.out.println("请输入手机号：");
        String phone = sc.next();

        System.out.println("请输入地址：");
        String address = sc.next();

        // 默认角色为 'user'
        String role = "user";

        // 创建 UserBean 对象，包含 role 字段
        UserBean user = new UserBean(0, username, password, phone, null, 0.0, address, role);

        if (userdao.register(user)) {
            System.out.println("注册成功！");
        } else {
            System.out.println("注册失败，请稍后再试！");
        }
    }


    /**
     * 用户登录并持久化用户数据到文件
     */
    public UserBean login() {
        System.out.println("请输入账号：");
        String username = sc.next();
        System.out.println("请输入密码：");
        String password = sc.next();

        UserBean user = userdao.login(username, password);
        if (user != null) {
            if (saveUserInfo(user)) {
                System.out.println("欢迎回来，" + user.getUsername() + "！");
                return user;
            } else {
                System.out.println("登录信息保存失败！");
            }
        } else {
            System.out.println("账号或密码错误！");
        }
        return null;
    }

    /**
     * 自动免密登录
     */
    @SneakyThrows
    public UserBean autoLogin() {
        File folder = new File("D:\\");
        File[] files = folder.listFiles((dir, name) -> name.startsWith("Glamshop_login_temp_") && name.endsWith(".txt"));

        if (files != null && files.length > 0) {
            File latestFile = files[0];
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(latestFile));
            UserBean user = (UserBean) ois.readObject();
            ois.close();
            System.out.println("检测到免密登录用户：" + user.getUsername());
            return user;
        }
        return null;
    }

    /**
     * 清除临时登录文件
     */
    public void clearTemporaryFiles() {
        File folder = new File("D:\\");
        File[] files = folder.listFiles((dir, name) -> name.startsWith("Glamshop_login_temp_") && name.endsWith(".txt"));

        if (files != null) {
            for (File file : files) {
                if (file.delete()) {
                    System.out.println("临时文件 " + file.getName() + " 已删除！");
                }
            }
        }
    }

    /**
     * 保存登录用户信息到本地文件
     */
    @SneakyThrows
    private boolean saveUserInfo(UserBean userBean) {
        boolean flag = false;
        try {
            File file = new File("D:\\Glamshop_login_temp_" + userBean.getUsername() + ".txt");
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(userBean);
            oos.close();
            flag = true;
        } catch (Exception e) {
            System.out.println("写入用户信息错误：" + e.getMessage());
        }
        return flag;
    }

    /**
     * 更新用户信息
     */
    public UserBean updateUserInfo(UserBean currentUser) {
        System.out.println("当前手机号：" + currentUser.getPhone());
        System.out.println("请输入新手机号：");
        String newPhone = sc.next();

        System.out.println("当前地址：" + currentUser.getAddress());
        System.out.println("请输入新地址：");
        String newAddress = sc.next();

        currentUser.setPhone(newPhone);
        currentUser.setAddress(newAddress);

        if (userdao.updateUser(currentUser)) {
            System.out.println("信息更新成功！");
            saveUserInfo(currentUser); // 同步更新到文件
            return currentUser;
        } else {
            System.out.println("信息更新失败！");
            return currentUser;
        }
    }

    /**
     * 找回密码
     */
    public void recoverPassword() {
        System.out.println("请输入账号：");
        String username = sc.next();
        System.out.println("请输入注册时的手机号：");
        String phone = sc.next();

        // 检查账号与手机号是否匹配
        if (userdao.recoverPassword(username, phone)) {
            System.out.println("验证成功！请输入新密码：");
            String newPassword = sc.next();

            // 更新密码
            if (userdao.resetPassword(username, newPassword)) {
                System.out.println("密码重置成功！您可以用新密码登录了。");
            } else {
                System.out.println("密码重置失败，请稍后重试！");
            }
        } else {
            System.out.println("账号或手机号不匹配！请确认信息后重试。");
        }
    }

    /**
     * 管理员登录
     */
    public AdminBean adminLogin() {
        System.out.println("请输入管理员用户名：");
        String username = sc.next();
        System.out.println("请输入管理员密码：");
        String password = sc.next();

        AdminBean admin = adminDao.login(username, password);
        if (admin != null) {
            System.out.println("欢迎管理员：" + admin.getUsername());
            return admin;
        } else {
            System.out.println("管理员登录失败！用户名或密码错误！");
        }
        return null;
    }
}
